package com.jackrain.nea.omslocal.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jackrain.nea.config.PropertiesConf;
import com.jackrain.nea.omslocal.conf.LoadCloumnsConfig;
import com.jackrain.nea.omslocal.util.SplitArrUtil;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.web.query.QueryEngine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * Description: 循环遍历同步库存表,查询到需要更新的数据就以消息形式发送
 * Created with IntelliJ IDEA.
 * User: cs
 * Date: 2017/4/13
 * Time: 14:19
 */
@Component
@Slf4j
public class QuantityQueryService {

    @Autowired
    private SendMqServies sendMq;
    @Autowired
    private ChangeQtyStatusService changeQtyStatusService;
    @Autowired
    private LoadCloumnsConfig loadCloumnsConfig;
    @Autowired
    private PropertiesConf pconf;
    @Autowired
    private LocalLogService localLogService;
    @Autowired
    private SplitArrUtil splitArrUtil;

    /**
     * 库存启动
     */
    public void qtyStart() {
        // 获取自身 bean
        QuantityQueryService quantityQueryService = ApplicationContextHandle.getBean(QuantityQueryService.class);
        quantityQueryService.queryQty();
    }

    /**
     * 库存启动
     */
    public void qtyJdStart() {
        // 获取自身 bean
        QuantityQueryService quantityQueryService = ApplicationContextHandle.getBean(QuantityQueryService.class);
        quantityQueryService.queryJdQty();
    }

    /**
     * 循环遍历查询库存异动表,发出待更新库存
     *
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public void queryQty() {

        String tag = pconf.getProperty("ons.qtytag", "updateQty");
        String topic = pconf.getProperty("ons.qtyunorderTopic", "BURGEON_QTY");
        int senNum = pconf.getPropertyInt("ons.sendnum");
        try {
            // 需要查询的字段
            String files = (String) LoadCloumnsConfig.qutycolsmap.get(pconf.getProperty("ons.qtytable"));
            int rownums = pconf.getPropertyInt("ons.rownum");
            // 查询同步库存表中等待同步的总数
            String countSql = "select " + files + " from T_IESSYNSTOCKMQ where synstatus = 0 and (platform =2 or platform = 3) and syncnum >= 0 and creationdate >= sysdate - 2/1440 and  rownum <= " + rownums + " order by creationdate,id for update skip locked";
            JSONArray jsonArr = QueryEngine.getInstance().doQueryObjectArray(countSql);

            // 有需要更新的库存数据 将查询到的数据以消息形式发送
            if (jsonArr == null || jsonArr.isEmpty()) {
                log.debug("jsonArr is null，no data to send");
                return;
            }

            if (jsonArr.size() > senNum) {

                JSONArray dataArr = splitArrUtil.splitArr(jsonArr, senNum);
                for (Object obj : dataArr) {
                    JSONArray array = JSONArray.parseArray(obj.toString());
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("data", array.toJSONString());
                    jsonObject.put("sendtime", System.currentTimeMillis());
                    String msgKey =sendMq.sendMqinfoObj(jsonObject, topic, tag);
                    if (!msgKey.equals("-1") ){
                        // 更改库存状态
                        changeQtyStatusService.changeStatus(array,msgKey);
                    }else {
                        log.error("库存消息发送失败，不更改状态");
                    }
                }

            } else {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("data", jsonArr.toJSONString());
                jsonObject.put("sendtime", System.currentTimeMillis());
                String msgKey = sendMq.sendMqinfoObj(jsonObject, topic, tag);
                if (!msgKey.equals("-1")){
                    // 更改库存状态
                    changeQtyStatusService.changeStatus(jsonArr,msgKey);
                }else {
                    log.error("库存消息发送失败，不更改状态");
                }
            }


        } catch (Exception e) {
            //  发送库存消息出现异常,将 异常记录到本地数据库
            localLogService.insertLogQty(e.getMessage(), pconf.getProperty("ons.qtytag", "updateQty"), pconf.getProperty("ons.qtyTopic", "BURGEON_QTY"), "消息未发出");
        }

    }

    /**
     * 循环遍历查询库存异动表,发出京东待更新库存
     *
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public void queryJdQty() {

        String tag = pconf.getProperty("ons.qtytag", "updateQty");
        String topic = pconf.getProperty("ons.qtyunorderTopic", "BURGEON_QTY");
        int senNum = pconf.getPropertyInt("ons.sendnum");

        try {
            // 需要查询的字段
            String files = (String) LoadCloumnsConfig.qutycolsmap.get(pconf.getProperty("ons.qtytable"));
            int rownums = pconf.getPropertyInt("ons.rownum");
            // 查询同步库存表中等待同步的总数
            String countSql = "select " + files + " from T_IESSYNSTOCKMQ where synstatus = 0 and platform =4 and syncnum >= 0 and creationdate >= sysdate - 2/1440 and  rownum <= " + rownums + " order by creationdate,id for update skip locked";
            JSONArray jsonArr = QueryEngine.getInstance().doQueryObjectArray(countSql);

            // 有需要更新的库存数据 将查询到的数据以消息形式发送
            if (jsonArr == null || jsonArr.isEmpty()) {
                log.debug("jsonArr is null");
                return;
            }

            if (jsonArr.size() > senNum) {

                log.debug("qty num :" + jsonArr.size());
                JSONArray dataArr = splitArrUtil.splitArr(jsonArr, senNum);
                for (Object obj : dataArr) {
                    JSONArray array = JSONArray.parseArray(obj.toString());
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("data", array.toJSONString());
                    jsonObject.put("sendtime", System.currentTimeMillis());
                    String msgKey = sendMq.sendMqinfoObj(jsonObject, topic, tag);
                    // 更改库存状态
                    changeQtyStatusService.changeStatus(jsonArr,msgKey);
                }

            } else {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("data", jsonArr.toJSONString());
                jsonObject.put("sendtime", System.currentTimeMillis());
                String msgKey = sendMq.sendMqinfoObj(jsonObject, topic, tag);
                // 更改库存状态
                changeQtyStatusService.changeStatus(jsonArr,msgKey);
            }

        } catch (Exception e) {
            //  发送库存消息出现异常,将 异常记录到本地数据库
            localLogService.insertLogQty(e.getMessage(), pconf.getProperty("ons.qtytag", "updateQty"), pconf.getProperty("ons.qtyTopic", "BURGEON_QTY"), "消息未发出");
        }

    }

}
